package cn.dglydrpy.fundmanagement.service.impl;

import cn.dglydrpy.fundmanagement.dao.entiey.Transaction;
import cn.dglydrpy.fundmanagement.dao.mapper.TransactionMapper;
import cn.dglydrpy.fundmanagement.service.ITransactionService;
import cn.dglydrpy.fundmanagement.service.dto.TransactionDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TransactionService implements ITransactionService {

    @Autowired
    private TransactionMapper transactionMapper;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public int saveTransaction(TransactionDto transactionDto) {
        Transaction transaction = new Transaction();
        BeanUtils.copyProperties(transactionDto, transaction);
        transaction.setCreatedTime(sdf.format(new Date()));
        transaction.setUpdatedTime(sdf.format(new Date()));
        if (transaction.getStatus() == null || transaction.getStatus().isEmpty()) {
            transaction.setStatus("1"); // 1-有效 0-无效
        }
        
        // 计算交易金额 = 份额 * 价格 +/- 费用
        if (transaction.getAmount() == null) {
            BigDecimal amount = transaction.getShares().multiply(transaction.getPrice());
            if ("1".equals(transaction.getTransactionType())) { // 买入
                amount = amount.add(transaction.getFee() != null ? transaction.getFee() : BigDecimal.ZERO);
            } else if ("2".equals(transaction.getTransactionType())) { // 卖出
                amount = amount.subtract(transaction.getFee() != null ? transaction.getFee() : BigDecimal.ZERO);
            }
            transaction.setAmount(amount);
        }
        
        return transactionMapper.insert(transaction);
    }

    @Override
    public void updateTransaction(TransactionDto transactionDto) {
        Transaction transaction = new Transaction();
        BeanUtils.copyProperties(transactionDto, transaction);
        transaction.setUpdatedTime(sdf.format(new Date()));
        transactionMapper.updateById(transaction);
    }

    @Override
    public void deleteTransaction(Long id) {
        transactionMapper.deleteById(id);
    }

    @Override
    public TransactionDto getTransactionById(Long id) {
        Transaction transaction = transactionMapper.selectById(id);
        if (transaction == null) {
            return null;
        }
        TransactionDto transactionDto = new TransactionDto();
        BeanUtils.copyProperties(transaction, transactionDto);
        setTransactionTypeName(transactionDto);
        return transactionDto;
    }

    @Override
    public Page<TransactionDto> getTransactionsByConditions(String fundCode, String transactionType, int pageNo, int pageSize) {
        Page<Transaction> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Transaction> queryWrapper = new QueryWrapper<>();
        if (fundCode != null && !fundCode.isEmpty()) {
            queryWrapper.like("fund_code", fundCode);
        }
        if (transactionType != null && !transactionType.isEmpty()) {
            queryWrapper.eq("transaction_type", transactionType);
        }
        queryWrapper.eq("status", "1");
        queryWrapper.orderByDesc("transaction_time");
        transactionMapper.selectPage(page, queryWrapper);

        Page<TransactionDto> dtoPage = new Page<>(pageNo, pageSize, page.getTotal());
        List<TransactionDto> records = page.getRecords().stream().map(transaction -> {
            TransactionDto dto = new TransactionDto();
            BeanUtils.copyProperties(transaction, dto);
            setTransactionTypeName(dto);
            return dto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(records);
        return dtoPage;
    }

    @Override
    public List<TransactionDto> getAllTransactions() {
        QueryWrapper<Transaction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        queryWrapper.orderByDesc("transaction_time");
        List<Transaction> transactions = transactionMapper.selectList(queryWrapper);
        return transactions.stream().map(transaction -> {
            TransactionDto dto = new TransactionDto();
            BeanUtils.copyProperties(transaction, dto);
            setTransactionTypeName(dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<TransactionDto> getTransactionsByFundCode(String fundCode) {
        QueryWrapper<Transaction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fund_code", fundCode);
        queryWrapper.eq("status", "1");
        queryWrapper.orderByAsc("transaction_time");
        List<Transaction> transactions = transactionMapper.selectList(queryWrapper);
        return transactions.stream().map(transaction -> {
            TransactionDto dto = new TransactionDto();
            BeanUtils.copyProperties(transaction, dto);
            setTransactionTypeName(dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public BigDecimal getTotalProfit() {
        // 这里应该实现基于交易记录和当前净值计算总盈亏的逻辑
        // 简化实现，实际应该查询所有基金的当前净值并计算
        return BigDecimal.ZERO;
    }

    private void setTransactionTypeName(TransactionDto dto) {
        if ("1".equals(dto.getTransactionType())) {
            dto.setTransactionTypeName("买入");
        } else if ("2".equals(dto.getTransactionType())) {
            dto.setTransactionTypeName("卖出");
        }
    }
}